package com.tledu.cyrus;

import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cyrus
 */
@WebServlet("/homework")
public class HomeworkServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 一、处理请求，解析参数
        // 二、进行业务处理，执行业务逻辑，组装返回数据
        // 三、对服务端进行响应

        // 查询所有的学生数据
        try {
            // 1. 通过jdbc连接进行数据查询
            //      1.1 引入jar包依赖
            //      1.2 装载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            //      1.3 获取连接
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/java34_student_manger",
                    "root",
                    "root"
            );
            //      1.4 编写sql
            String sql = "select * from student;";
            //      1.5 创建sql执行对象
            Statement stmt = conn.createStatement();
            //      1.6 执行sql
            ResultSet rs = stmt.executeQuery(sql);
            //      1.7 处理结果
            List<Student> students = new ArrayList<Student>();
            while (rs.next()) {
                students.add(new Student(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getInt("age"),
                        rs.getInt("sex"),
                        rs.getString("phone")
                ));
            }
            //      1.8 关闭连接
            stmt.close();
            conn.close();
            // 2. 给客户端响应
            //      2.1 设置响应的格式 application/json
            resp.setContentType("application/json;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            //      2.2 输出请求体，和响应格式匹配的请求体(JSON字符串)
            resp.getWriter().write(JSONObject.toJSONString(students));
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
